package com.ukao.pad.ui.recheck;


import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.pad.R;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.AddClothingItem;
import com.ukao.pad.bean.ProductRelImgBean;
import com.ukao.pad.bean.RecheckBean;
import com.ukao.pad.bean.StringBean;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.EditClotingDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.OnClothingListener;
import com.ukao.pad.presenter.RecheckPesenter;
import com.ukao.pad.ui.packPackag.PhotoActivity;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.RecheckView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * 开始复检
 */
public class RecheckFragment extends MvpFragment<RecheckPesenter> implements RecheckView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    @BindView(R.id.search_button)
    StateImageView searchButton;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.tv_store_name)
    TextView factoryName;
    @BindView(R.id.productName)
    TextView productName;
    @BindView(R.id.serviceName)
    TextView serviceName;
    @BindView(R.id.addServiceDesc)
    TextView addServiceDesc;
    @BindView(R.id.annexDesc)
    TextView annexDesc;
    @BindView(R.id.annexDesc_btn)
    StateImageView annexDescBtn;
    @BindView(R.id.productImgCnt)
    TextView productImgCnt;
    @BindView(R.id.productImgCnt_btn)
    StateImageView productImgCntBtn;
    @BindView(R.id.brandName)
    TextView brandName;
    @BindView(R.id.brandName_btn)
    StateImageView brandNameBtn;
    @BindView(R.id.colorDesc)
    TextView colorDesc;
    @BindView(R.id.colorDesc_btn)
    StateImageView colorDescBtn;
    @BindView(R.id.flawDesc)
    TextView flawDesc;
    @BindView(R.id.flawDesc_btn)
    StateImageView flawDescBtn;
    @BindView(R.id.effectDesc)
    TextView effectDesc;
    @BindView(R.id.effectDesc_btn)
    StateImageView effectDescBtn;
    @BindView(R.id.operating_txt)
    TextView operatingTxt;
    @BindView(R.id.rewashing_btn)
    StateButton rewashingBtn;
    @BindView(R.id.print_qualified_btn)
    StateButton strikeBtn;
    @BindView(R.id.search_edit_text)
    ClearEditText searchEditText;
    @BindView(R.id.center_layout)
    LinearLayout centerLayout;
    @BindView(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R.id.tv_title)
    TextView title;
    @BindView(R.id.factoryShelfNo)
    TextView factoryShelfNo;
    @BindView(R.id.print_receipt_btn)
    StateButton printBtn;
    @BindView(R.id.rifd_btn)
    StateImageView rifdBtn;
    @BindView(R.id.radio_button1)
    RadioButton radioButton1;
    @BindView(R.id.radio_button2)
    RadioButton radioButton2;
    @BindView(R.id.segmented_group)
    SegmentedGroup segmentedGroup;


    private String mParam1;
    private String mParam2;
    private RecheckBean.ProductInfoBean mProListBean;
    private List<AddClothingItem> mAnnexDescData;
    private EditClotingDialogFragment mAnnexDescDialog;

    public String strannexDesc; /*附件*/
    private List<AddClothingItem> mEffectData;
    private List<AddClothingItem> mFlawData;
    private List<AddClothingItem> mColorData;
    private List<AddClothingItem> mBrandData;
    private ArrayList<StringBean> mAnnexDesclist;
    private ArrayList<StringBean> meffectDesclist;
    private ArrayList<StringBean> mflawDesclist;
    private ArrayList<StringBean> mColorDesclist;
    private ArrayList<StringBean> mBrandDesclist = new ArrayList<>();
    private ArrayList<String> mPhotoData = new ArrayList<>();
    private String businessId;
    public String strflawDesc;
    public String streffectDesc;
    public String strolorDesc;/*颜色附件*/
    public String strbrandId;/*品牌id*/
    private String strbrandName;/*品牌*/
    private String mId;/*衣物ID*/

    private ArrayList<StringBean> mSelectDesclist;/*返回选中的集合*/
    private String descJson; /*返回选中的json*/
    private String selectName;/*选中返回的文本*/
    /*为了防止修改失败*/
    private String strbrandNames;
    private String strbrandIds;
    private String strolorDescs;
    private String streffectDescs;
    private String strflawDescs;
    private String strannexDescs;

    public static RecheckFragment newInstance(String param1, String param2) {
        RecheckFragment fragment = new RecheckFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected RecheckPesenter createPresenter() {
        return new RecheckPesenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recheck, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }
    @Override
    protected void initView() {
        String name = SaveParamets.getValname();
        title.setText(name);
        operatingTxt.setText("已操作" + "【" + name + "】");
        rewashingBtn.setVisibility(View.GONE);
        searchEditText.requestFocus();
        strikeBtn.setVisibility(View.GONE);
        strikeBtn.setText("打标");
        UsbrfidReaderHelper.getInstance().readCardNum();
    }


    @Override
    protected void initListener() {
        super.initListener();
        searchEditText.setOnEditorActionListener(mOnEditorAction);

    }


    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {

                searchScanCode();
                hideSoftInput();


            }
            return false;
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {

        switch (event.getMessage()) {
            case cardNum:/*成功*/
                String rfidSecretCard = (String) event.getData();
                searchEditText.setText(rfidSecretCard);
                searchScanCode();
                break;


        }
    }
    @OnClick({R.id.productImgCnt_btn, R.id.rewashing_btn, R.id.print_qualified_btn, R.id.annexDesc_btn, R.id.search_button,
            R.id.brandName_btn, R.id.colorDesc_btn, R.id.flawDesc_btn, R.id.effectDesc_btn,R.id.rifd_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case  R.id.rifd_btn:
                UsbrfidReaderHelper.getInstance().readCardNum();
                break;
            case R.id.rewashing_btn:
                break;
            case R.id.print_qualified_btn:


                break;

            case R.id.search_button:

                searchScanCode();
                hideSoftInput();
                break;
            case R.id.annexDesc_btn:  /*附件*/
                requestData(mAnnexDescData, mAnnexDesclist, 1, "附件");
                break;
            case R.id.brandName_btn:  /*品牌*/
                requestData(mBrandData, mBrandDesclist, 2, "品牌");
                break;
            case R.id.colorDesc_btn:/*颜色*/

                requestData(mColorData, mColorDesclist, 3, "颜色");
                break;
            case R.id.flawDesc_btn:/*瑕疵*/

                requestData(mFlawData, mflawDesclist, 4, "瑕疵");
                break;
            case R.id.effectDesc_btn:/*洗后效果*/
                requestData(mEffectData, meffectDesclist, 5, "洗后效果");

                break;
            case R.id.productImgCnt_btn: /*查看图片*/
                if (CheckUtils.isEmpty(mPhotoData)) return;
                Intent mIntent = new Intent(_mActivity, PhotoActivity.class);
                mIntent.putStringArrayListExtra(ARG_PARAM1, mPhotoData);
                mIntent.putExtra(ARG_PARAM2, 0);
                startActivity(mIntent);
                break;

        }
    }

    private void searchScanCode() {
        String strscanCode = getText(searchEditText);
        if (strscanCode.isEmpty()) return;
        mvpPresenter.stationScanCode(_mActivity, strscanCode);
    }

    /**
     * @param mEffectData     附件列表
     * @param meffectDesclist 选中附件的列表
     */
    private void requestData(List<AddClothingItem> mEffectData, ArrayList<StringBean> meffectDesclist, int pos, String title) {
        if (!CheckUtils.isNull(mProListBean) && CheckUtils.isEmpty(mEffectData)) {
            if (pos == 1) {
                mvpPresenter.annexDescRequest(businessId);
            } else {
                mvpPresenter.projectData(pos);
            }

        } else if (!CheckUtils.isNull(mProListBean)) {
            boolean isSing = false;
            if (pos == 2) {
                isSing = true;
            }
            showAnnexDescDialog((ArrayList<AddClothingItem>) mEffectData, meffectDesclist, pos, isSing, title);
        }
    }


    @Override
    public void loadStockReworkSucceed(RecheckBean mRecheckBean) {
        cleanCode();
        cleanaallData();
        if (!CheckUtils.isEmpty(mRecheckBean.getErrorMsg())) {
            T.show(mRecheckBean.getErrorMsg());
        }
        centerLayout.setVisibility(View.VISIBLE);
        bottomLayout.setVisibility(View.VISIBLE);
        mProListBean = mRecheckBean.getProductInfo();
        businessId = mProListBean.getBusinessId();
        statusText.setText(CheckUtils.isEmptyString(mProListBean.getStatusText()));
        factoryName.setText(CheckUtils.isEmptyString(mProListBean.getFactoryCode()) + " " + mProListBean.getFactoryName());
        productName.setText(mProListBean.getProductName());
        serviceName.setText(mProListBean.getServiceName());
        brandName.setText(CheckUtils.isEmptyString(mProListBean.getBrandName()));
        productImgCnt.setText(CheckUtils.isEmptyString(mProListBean.getProductImgCnt()));
        mId = mProListBean.getId();
        strbrandName = mProListBean.getBrandName();
        strbrandId = mProListBean.getId();
        strolorDesc = mProListBean.getColorDesc();
        streffectDesc = mProListBean.getEffectDesc();
        strflawDesc = mProListBean.getFlawDesc();
        strannexDesc = mProListBean.getAnnexDesc();
        mBrandDesclist.clear();
        mBrandDesclist.add(new StringBean(strbrandId, strbrandName));

        mPhotoData.clear();
        List<ProductRelImgBean> mProductImgData = mRecheckBean.getProductImgList();
        for (ProductRelImgBean productRelImgBean : mProductImgData) {
            mPhotoData.add(productRelImgBean.getCameraImg());
        }
        Gson mGson = new Gson();
        if (!CheckUtils.isEmpty(mProListBean.getAddServiceDesc())) {
            List<StringBean> mServiceDesclist = mGson.fromJson(mProListBean.getAddServiceDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String service = "";
            for (StringBean item : mServiceDesclist) {
                service = service + item.getName() + CheckUtils.isEmptyNumber(item.getAmt()) + "元" + ",";
            }
            if (service.endsWith(","))
                service = service.substring(0, service.length() - 1);
            addServiceDesc.setText(service); /* 附加f服务  */
        } else {
            addServiceDesc.setText("");
        }


        if (!CheckUtils.isEmpty(mProListBean.getAnnexDesc())) {
            mAnnexDesclist = mGson.fromJson(mProListBean.getAnnexDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String annex = "";
            for (StringBean item : mAnnexDesclist) {
                annex = annex + item.getName() + "/";

            }
            if (annex.endsWith("/"))
                annex = annex.substring(0, annex.length() - 1);
            annexDesc.setText(annex); /* 附件   */

        } else {
            annexDesc.setText("");
        }
        if (!CheckUtils.isEmpty(mProListBean.getColorDesc())) {
            mColorDesclist = mGson.fromJson(mProListBean.getColorDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String color = "";
            for (StringBean item : mColorDesclist) {
                color = color + item.getName() + "/";
            }
            if (color.endsWith("/"))
                color = color.substring(0, color.length() - 1);
            colorDesc.setText(color); /* 颜色  */
        } else {
            colorDesc.setText("");
        }

        if (!CheckUtils.isEmpty(mProListBean.getFlawDesc())) {
            mflawDesclist = mGson.fromJson(mProListBean.getFlawDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String strflawDesc = "";
            for (StringBean item : mflawDesclist) {
                strflawDesc = strflawDesc + item.getName() + "/";
            }
            if (strflawDesc.endsWith("/"))
                strflawDesc = strflawDesc.substring(0, strflawDesc.length() - 1);
            flawDesc.setText(strflawDesc); /*瑕疵*/
        } else {
            flawDesc.setText("");
        }
        if (!CheckUtils.isEmpty(mProListBean.getEffectDesc())) {
            meffectDesclist = mGson.fromJson(mProListBean.getEffectDesc(),
                    new TypeToken<List<StringBean>>() {
                    }.getType());
            String streffectDesc = "";
            for (StringBean item : meffectDesclist) {
                streffectDesc = streffectDesc + item.getName() + "/";
            }
            if (streffectDesc.endsWith("/"))
                streffectDesc = streffectDesc.substring(0, streffectDesc.length() - 1);
            effectDesc.setText(streffectDesc); /*洗后效果*/
        } else {
            effectDesc.setText("");
        }
    }

    private void cleanaallData() {

    }

    @Override
    public void loadFail(String error) {
        T.show(error);
    }


    /**
     * 品牌
     */
    @Override
    public void loadBrandData(List<AddClothingItem> mDescData) {
        this.mBrandData = mDescData;
        showAnnexDescDialog((ArrayList<AddClothingItem>) mDescData, mBrandDesclist, 2, true, "品牌");
    }

    /**
     * 颜色
     */
    @Override
    public void loadColorData(List<AddClothingItem> mDescData) {
        this.mColorData = mDescData;
        showAnnexDescDialog((ArrayList<AddClothingItem>) mDescData, mColorDesclist, 3, true, "颜色");
    }

    /**
     * 瑕疵
     */
    @Override
    public void loadFlawData(List<AddClothingItem> mDescData) {
        this.mFlawData = mDescData;
        showAnnexDescDialog((ArrayList<AddClothingItem>) mDescData, mflawDesclist, 4, false, "瑕疵");
    }

    /**
     * 洗后效果
     */
    @Override
    public void loadEffectData(List<AddClothingItem> mDescData) {
        this.mEffectData = mDescData;
        showAnnexDescDialog((ArrayList<AddClothingItem>) mDescData, meffectDesclist, 5, false, "洗后效果");
    }


    /**
     * 附件
     */
    @Override
    public void annexDescSucceed(List<AddClothingItem> mAnnexDescData) {
        this.mAnnexDescData = mAnnexDescData;
        showAnnexDescDialog((ArrayList<AddClothingItem>) mAnnexDescData, mAnnexDesclist, 1, false, "附件");
    }

    @Override
    public void loadStockReworkFail(String msg) {

        cleanCode();
        T.show(msg);
    }


    /**
     * 附件弹窗
     *
     * @param mDesclist       附件列表
     * @param mSelectDesclist 选中的附件
     * @param typeEnter       进入类型
     */
    private void showAnnexDescDialog(ArrayList<AddClothingItem> mDesclist, ArrayList<StringBean> mSelectDesclist, int typeEnter, boolean isSingle, String title) {
        mAnnexDescDialog = new EditClotingDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(ARG_PARAM1, mDesclist);
        bundle.putInt(ARG_PARAM2, typeEnter);
        bundle.putParcelableArrayList(ARG_PARAM3, mSelectDesclist);
        bundle.putBoolean(ARG_PARAM4, isSingle);
        bundle.putString(ARG_PARAM5, title);

        mAnnexDescDialog.setOnClothingListener(mOnClothingListener);
        mAnnexDescDialog.setArguments(bundle);
        mAnnexDescDialog.show(getChildFragmentManager(), EditClotingDialogFragment.class.getName());
    }

    private OnClothingListener mOnClothingListener = new OnClothingListener() {

        /**
         *
         * @param mSelectDesclist  选中的附件列表
         * @param descJson    json 格式
         * @param selectName  显示的数据
         * @param pos         那个附件调用
         */
        @Override
        public void onItemSelect(ArrayList<StringBean> mSelectDesclist, String descJson, String selectName, int pos) {
            RecheckFragment.this.mSelectDesclist = mSelectDesclist;
            RecheckFragment.this.descJson = descJson;
            RecheckFragment.this.selectName = selectName;
            switch (pos) {
                case 1: /*附件*/
                    strannexDesc = descJson;
                    submitProductUpdate(pos);
                    break;
                case 2:  /*品牌 */
                    strbrandName = mSelectDesclist.get(0).getName();
                    strbrandId = mSelectDesclist.get(0).getId();

                    submitProductUpdate(pos);
                    break;
                case 3:/*颜色*/

                    strolorDesc = descJson;
                    submitProductUpdate(pos);
                    break;
                case 4:/*瑕疵*/

                    strflawDesc = descJson;
                    submitProductUpdate(pos);
                    break;
                case 5:/*洗后效果*/
                    streffectDesc = descJson;
                    submitProductUpdate(pos);

                    break;

            }
        }
    };

    /**
     * 提交修改的信息
     */
    private void submitProductUpdate(int pos) {

        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("id", mId);/*衣物id*/
        if (!CheckUtils.isNull(strbrandId)) mHashMap.put("brandId", strbrandId);/*品牌id*/
        if (!CheckUtils.isNull(strbrandName)) mHashMap.put("brandName", strbrandName);/*品牌名称*/
        if (!CheckUtils.isNull(strolorDesc)) mHashMap.put("colorDesc", strolorDesc);/*颜色描述*/
        if (!CheckUtils.isNull(streffectDesc)) mHashMap.put("effectDesc", streffectDesc);/*洗后效果描述*/
        if (!CheckUtils.isNull(strflawDesc)) mHashMap.put("flawDesc", strflawDesc);/*瑕疵描述*/
        if (!CheckUtils.isNull(strannexDesc)) mHashMap.put("annexDesc", strannexDesc);/*附件描述*/
        mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
        mvpPresenter.orderProductUpdate(mHashMap, pos);
    }

    /**
     * 提交成功
     *
     * @param pos 是修改了那一个
     */
    @Override
    public void loadUpdataSucceed(int pos) {
        switch (pos) {
            case 1: /*附件*/
                strannexDescs = descJson;
                mAnnexDesclist = mSelectDesclist;
                annexDesc.setText(selectName);
                break;
            case 2:  /*品牌*/
                strbrandNames = strbrandName;
                strbrandIds = strbrandId;
                mBrandDesclist = mSelectDesclist;
                brandName.setText(selectName);
                break;
            case 3:/*颜色*/
                mColorDesclist = mSelectDesclist;
                strolorDescs = descJson;
                colorDesc.setText(selectName);
                break;
            case 4:/*瑕疵*/
                mflawDesclist = mSelectDesclist;
                strflawDescs = descJson;
                flawDesc.setText(selectName);

                break;
            case 5:/*洗后效果*/
                meffectDesclist = mSelectDesclist;
                streffectDescs = descJson;
                effectDesc.setText(selectName);


                break;

        }
    }

    /**
     * 修改失败
     *
     * @param error
     * @param pos   是修改了那一个失败
     */
    @Override
    public void loadUpdataFail(String error, int pos) {
        T.show(error);
        switch (pos) {
            case 1: /*附件*/
                strannexDesc = strannexDescs;
                break;
            case 2:  /*品牌*/
                strbrandName = strbrandNames;
                strbrandId = strbrandIds;
                break;
            case 3:/*颜色*/
                strolorDesc = strolorDescs;
                break;
            case 4:/*瑕疵*/
                strflawDesc = strflawDescs;
                break;
            case 5:/*洗后效果*/
                streffectDesc = streffectDescs;

                break;

        }
    }

    private void cleanCode() {
        searchEditText.setText("");
        searchEditText.requestFocus();
        KeyBoardUtil.hideInputmethod(searchEditText);


    }
}